import java.util.Arrays;

/**
 * @author : zzr
 * @description :模拟实现栈
 * @date :
 */
public class MyStack {
    private int[] elem;
    private int usedSize;

    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 不带参数的栈，默认长度为 10
     */
    public MyStack() {
        this.elem = new int[DEFAULT_CAPACITY];
    }

    /**
     * 压栈操作
     *
     * @param val
     */
    public void push(int val) {
        if (isFull()) {
            //如果满了，就扩容
            this.elem = Arrays.copyOf(this.elem, this.elem.length * 2); // 2倍扩容
        }
        this.elem[this.usedSize] = val; //useSize默认值为0
        this.usedSize++;
    }

    /**
     * 判断栈是否满
     *
     * @return
     */
    private boolean isFull() {
        return this.elem.length == usedSize;
    }

    /**
     * 判断栈是否为空
     * @return
     */
    private boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 出栈操作
     *
     * @return
     */
    public int pop() {
        if (isEmpty()) {
            throw new StackIsEmptyException("栈为空");
        }
        int oldVal = elem[usedSize - 1]; //记录弹出的元素
        usedSize--;
        return oldVal;
    }

    /**
     * 获取栈顶元素，但并不弹出栈顶元素
     * @return
     */
    public int peek() {
        if (isEmpty()) {
            throw new StackIsEmptyException("栈为空");
        }
        return elem[usedSize - 1];
    }


}
